package com.hyg.lib_music.ui.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;

import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.Base.BaseApplication;
import com.hyg.lib_common.DataModel.Music.Music;
import com.hyg.lib_common.DataModel.Music.MusicCateData;
import com.hyg.lib_common.DataModel.Music.MusicCategoryData;
import com.hyg.lib_music.R;
import com.hyg.lib_music.adapter.TabPagerAdapter;
import com.hyg.lib_music.service.MusicService;
import com.hyg.lib_music.ui.fragment.BaseFragment;
import com.hyg.lib_music.ui.fragment.MusicCateListFragment;
import com.hyg.lib_music.ui.fragment.MusicCategoryListFragment;
import com.hyg.lib_music.ui.fragment.MusicDocListFragment;
import com.hyg.lib_music.ui.fragment.MusicListFragment;
import com.hyg.lib_music.ui.view.MusicPlayView;
import com.hyg.lib_music.util.MusicFavManager;
import com.hyg.lib_music.util.SrceenUtils;
import com.hyg.lib_music.util.TimeUtils;

import java.util.ArrayList;
import java.util.List;


public class MusicListActivity extends BaseActivity implements View.OnClickListener {

    private MusicCategoryData mCategory;
    private MusicCateData mCate;
    private ViewPager viewPager;
    private TabPagerAdapter mAdapter;

    private ImageView back;
    private ImageView musicClock;

    public MusicPlayView musicPlayView;//播放器
    private List<BaseFragment> fragmentList;//容器集合
    private MusicService.MusicServiceBinder serviceBinder;

    private int stopSecond = 60;//倒计时
//    private Timer mTimer = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_list);
        //设置紫色状态栏
        StatusBarUtil.setStatusBar(1, this, getResources().getColor(R.color.musicPrimary), 60, null, null, false);

        init();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
//        stopTimer();
        unbindService(mServiceConnection);
    }

    // 控件监听
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.play_pre) {// 上一首
            serviceBinder.playNext();
        } else if (id == R.id.play_next) {// 下一首
            serviceBinder.playPre();
        } else if (id == R.id.play_or_pause) {// 播放或暂停
            serviceBinder.playOrPause();
            //            case R.id.playing_list:
            // 播放列表
//                showPlayList();
//                break;
        } else if (id == R.id.back) {
            finish();
            overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
        } else if (id == R.id.music_clock) {
            showTimerDialog();
        } else if (id == R.id.music_type_order) {
            serviceBinder.setPlayMode(MusicService.TYPE_ORDER);
            musicPlayView.updateMusicType(MusicService.TYPE_ORDER);
//                Toast.makeText(MainMusicBedActivity.this, "列表循环", Toast.LENGTH_SHORT).show();
        } else if (id == R.id.music_type_single) {
            serviceBinder.setPlayMode(MusicService.TYPE_SINGLE);
            musicPlayView.updateMusicType(MusicService.TYPE_SINGLE);
//                Toast.makeText(MainMusicBedActivity.this, "单曲循环", Toast.LENGTH_SHORT).show();
        } else if (id == R.id.music_type_random) {
            serviceBinder.setPlayMode(MusicService.TYPE_RANDOM);
            musicPlayView.updateMusicType(MusicService.TYPE_RANDOM);
//                Toast.makeText(MainMusicBedActivity.this, "随机播放", Toast.LENGTH_SHORT).show();
        }
    }

    private void init() {

        //音乐分类
        mCategory = (MusicCategoryData) getIntent().getExtras().getSerializable("category");
        //知识分类
        mCate = (MusicCateData) getIntent().getExtras().getSerializable("cate");

        viewPager = this.findViewById(R.id.tab_viewPager);
        musicPlayView = this.findViewById(R.id.musicPlayView);
        //返回按钮
        back = (ImageView) findViewById(R.id.back);
        musicClock = (ImageView) findViewById(R.id.music_clock);

        fragmentList = new ArrayList<>();
        //TODO 测试
        if (mCategory != null) {

            if (mCategory.subList == null || mCategory.subList.size() == 0) {
                fragmentList.add(MusicListFragment.newInstance(mCategory));
            } else {
                fragmentList.add(
                        new MusicCategoryListFragment());
            }
        } else if (mCate != null) {

            if (mCate.subList == null || mCate.subList.size() == 0) {
                fragmentList.add(MusicDocListFragment.newInstance(mCate));
            } else {
                fragmentList.add(MusicCateListFragment.newInstance(mCate));
            }
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        //初始化 ViewPager
        mAdapter = new TabPagerAdapter(fragmentManager, fragmentList);
        viewPager.setAdapter(mAdapter);

        // 设置监听
        back.setOnClickListener(this);
        musicClock.setOnClickListener(this);
        musicPlayView.btnPlayMode.setOnClickListener(this);
        musicPlayView.btnPlayOrPause.setOnClickListener(this);
        musicPlayView.btnPlayPre.setOnClickListener(this);
        musicPlayView.btnPlayNext.setOnClickListener(this);
//        musicPlayView.btnPlayingList.setOnClickListener(this);
        musicPlayView.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                musicPlayView.indicatorView.setText(TimeUtils.formatTime((long) progress) + "/" + TimeUtils.formatTime((long) seekBar.getMax()));

                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) musicPlayView.indicatorView.getLayoutParams();
                float screenWidth = SrceenUtils.getScreenWidth(MusicListActivity.this);
                float indicatorViewWidth = musicPlayView.indicatorView.getWidth();
                float indicatorOffset = screenWidth * ((float) progress / seekBar.getMax()) - indicatorViewWidth / 2;
                if (indicatorOffset > 0 && indicatorOffset < screenWidth - (indicatorViewWidth)) {
                    params.leftMargin = (int) indicatorOffset;
                } else if (indicatorOffset > screenWidth - indicatorViewWidth) {
                    params.leftMargin = (int) (screenWidth - indicatorViewWidth);
                } else {
                    params.leftMargin = 0;
                }
                musicPlayView.indicatorView.setLayoutParams(params);

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                serviceBinder.seekTo(seekBar.getProgress());
            }
        });
        musicPlayView.btnTtypeSingle.setOnClickListener(this);
        musicPlayView.btnTtypeOrder.setOnClickListener(this);
        musicPlayView.btnTtypeRandom.setOnClickListener(this);
//        musicPlayView.fav.setOnClickListener(this);
        // 绑定service
        Intent i = new Intent(this, MusicService.class);
        bindService(i, mServiceConnection, BIND_AUTO_CREATE);
    }


    //定义与服务的连接的匿名类
    private ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //绑定成功后，取得MusicSercice提供的接口
            serviceBinder = (MusicService.MusicServiceBinder) service;
            //注册监听器
            serviceBinder.registerOnStateChangeListener(listenr);
            //获得当前音乐
            Music item = serviceBinder.getCurrentMusic();

            musicPlayView.seekBar.setEnabled(true);
            if (item == null) {
                //当前音乐为空, seekbar不可拖动
                musicPlayView.seekBar.setEnabled(false);
            } else if (serviceBinder.isPlaying()) {
                //如果正在播放音乐, 更新信息
                musicPlayView.musicTitleView.setText(item.musicName);
                String logoUrl = MusicFavManager.sharedManager().getLogoUrl(item.cateId);
                if (logoUrl != null && !logoUrl.isEmpty()) {
                    Glide.with(BaseApplication.getInstance()).load(logoUrl).error(R.mipmap.headimg).into(musicPlayView.musicImgView);
                }
                musicPlayView.btnPlayOrPause.setImageResource(R.mipmap.ic_music_pause);

            } else {
                //当前有可播放音乐但没有播放
                musicPlayView.musicTitleView.setText(item.musicName);
                String logoUrl = MusicFavManager.sharedManager().getLogoUrl(item.cateId);
                if (logoUrl != null && !logoUrl.isEmpty()) {
                    Glide.with(BaseApplication.getInstance()).load(logoUrl).error(R.mipmap.headimg).into(musicPlayView.musicImgView);
                }
                musicPlayView.btnPlayOrPause.setImageResource(R.mipmap.ic_music_play);

            }
            // 获取当前播放模式
            int mode = (serviceBinder.getPlayMode());
            musicPlayView.updateMusicType(mode);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //断开连接之后, 注销监听器
            serviceBinder.unregisterOnStateChangeListener(listenr);
        }
    };

    //实现监听器监听MusicService的变化，
    private MusicService.OnStateChangeListenr listenr = new MusicService.OnStateChangeListenr() {

        @Override
        public void onPlayProgressChange(long played, long duration) {
            musicPlayView.seekBar.setMax((int) duration);

            musicPlayView.seekBar.setProgress((int) played);
        }

        @Override
        public void onPlay(final Music item) {
            //变为播放状态时
            musicPlayView.musicTitleView.setText(item.musicName);
            String logoUrl = MusicFavManager.sharedManager().getLogoUrl(item.cateId);
            if (logoUrl != null && !logoUrl.isEmpty()) {
                Glide.with(BaseApplication.getInstance()).load(logoUrl).error(R.mipmap.headimg).into(musicPlayView.musicImgView);
            }
            musicPlayView.btnPlayOrPause.setImageResource(R.mipmap.ic_music_pause);
        }

        @Override
        public void onPause() {
            //变为暂停状态时
            musicPlayView.btnPlayOrPause.setImageResource(R.mipmap.ic_music_play);
        }
    };

    //音乐计时器
    private void showTimerDialog() {
        List hours = new ArrayList();
        List minutes = new ArrayList();
        for (int i = 0; i < 24; i++) {
            hours.add(i + " 小时");
        }
        for (int i = 1; i < 60; i++) {
            minutes.add(i + " 分钟");
        }
//        OptionsPickerView pvNoLinkOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
//
//            @Override
//            public void onOptionsSelect(int options1, int options2, int options3, View v) {
////                stopTimer();//停止上一次
//                //计算秒 注意分钟从1开始
//                stopSecond = options1*60*60 + (options2+1)*60;
//                serviceBinder.stopMusicAlarm(stopSecond);
////                startTimer();
//            }
//        })
//                .setTitleText("定时关闭")
//                .setSubmitText("开始计时")
//                .build();
//        pvNoLinkOptions.setNPicker(hours, minutes,null);
//        pvNoLinkOptions.show();
    }

//    //开始倒计时
//    private void startTimer() {
//        //获得当前音乐
//        Music item = serviceBinder.getCurrentMusic();
//        if(item == null || !serviceBinder.isPlaying()) {
//            new AlertDialog.Builder(MusicListActivity.this).setTitle("错误").setMessage("音乐没有在播放").show();
//            return;
//        }
//        if (mTimer == null) {
//            mTimer = new Timer(true);
//        }
//        mTimer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                if (0 == stopSecond) {
//                    stopTimer();
//                    MusicListActivity.this.runOnUiThread(new Runnable()
//                    {
//                        public void run()
//                        {
//                            //音乐暂停
//                            Music item = serviceBinder.getCurrentMusic();
//                            if(item != null && serviceBinder.isPlaying()) {
//                                serviceBinder.playOrPause();
//                            }
//                        }
//
//                    });
//                    return;
//                }
//                stopSecond--;
//            }
//        }, 0, 1000);
//    }
//
//    private void stopTimer() {
//        if (mTimer != null) {
//            mTimer.cancel();
//            mTimer = null;
//        }
//    }
}


